<template>
  <div class="eval-task-generator">
    <div 
      class="floating-window" 
      v-if="evaluationStore.showEvaluationCreator"
      :style="windowStyle"
    >
      <div 
        class="window-header" 
        @dblclick="toggleMaximize"
        @mousedown="startDrag"
      >
        <h2>创建评测任务</h2>
        <div class="window-controls">
          <button class="maximize-btn" @click.stop="toggleMaximize">
            {{ isMaximized ? '↗' : '□' }}
          </button>
          <button class="close-btn" @click.stop="evaluationStore.toggleEvaluationCreator(false)">×</button>
        </div>
      </div>
      
      <div class="window-content">
        <div v-if="errorMessage" class="error-message">
          {{ errorMessage }}
        </div>

        <div class="form-group">
          <label>任务标题：</label>
          <input 
            type="text" 
            v-model="evaluationStore.evaluationConfig.title" 
            placeholder="填写任务名称"
            class="task-title-input"
          >
        </div>

        <div class="form-group">
          <label>任务描述：</label>
          <textarea 
            v-model="evaluationStore.evaluationConfig.description" 
            placeholder="填写任务描述"
            class="task-description-input"
          ></textarea>
        </div>

        <div class="form-group">
          <label>评测prompt：</label>
          <textarea
            v-model="evaluationStore.evaluationConfig.prompt"
            placeholder="用于提示裁判模型按需生成评测报告"
            class="task-prompt-input">
          </textarea>
        </div>

        <div class="form-group">
          <label>选择裁判模型：</label>
          <div class="model-options-container">
            <div class="model-option" v-for="judge in availableJudges" :key="judge.id">
              <input 
                type="checkbox" 
                :value="judge.id"
                v-model="evaluationStore.evaluationConfig.judges"
              >
              <span>{{ judge.name }}</span>
            </div>
          </div>
        </div>

        <div class="form-group">
          <label>选择评测模型：</label>
          <div class="model-options-container">
            <div class="model-option" v-for="model in availableModels" :key="model.id">
              <input 
                type="checkbox" 
                :value="model.id"
                v-model="evaluationStore.evaluationConfig.models"
              >
              <span>{{ model.name }}</span>
            </div>
          </div>
        </div>

        <div class="form-group">
          <label>已选标准问题：</label>
          <div class="selected-items" v-if="evaluationStore.selectedQuestionIds.length > 0">
            <span 
              v-for="id in evaluationStore.selectedQuestionIds" 
              :key="id" 
              class="selected-item"
            >
              {{ id }}
              <button @click="removeQuestion(id)" class="remove-btn">×</button>
            </span>
          </div>
          <div v-else class="no-selection">
            请在标准问题管理页面勾选问题
          </div>
        </div>

        <div class="action-buttons">
          <button 
            @click="createEvaluationTask"
            :disabled="!canCreate || isLoading"
            class="create-btn"
          >
            {{ isLoading ? '创建中...' : '创建评测任务' }}
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref, computed, reactive } from 'vue'
import { useEvaluationStore } from '@/stores/evaluation.ts'
import { useVersionStore } from '@/stores/versionStore'
import { createTask } from '@/api/evaluation.ts'

const availableJudges = [
  { id: 'gpt-4-gizmo-*', name: 'GPT-4 Gizmo' },
  { id: 'gpt-4o', name: 'GPT-4o' },
  { id: 'deepseek-chat', name: 'DeepSeek Chat' },
  { id: 'deepseek-r1', name: 'DeepSeek R1' },
  { id: 'grok-3', name: 'Grok-3' },
  { id: 'grok-3-reasoning', name: 'Grok-3 Reasoning' }
]

const availableModels = [
  { id: 'gpt-4-gizmo-*', name: 'GPT-4 Gizmo' },
  { id: 'gpt-4o', name: 'GPT-4o' },
  { id: 'deepseek-chat', name: 'DeepSeek Chat' },
  { id: 'deepseek-r1', name: 'DeepSeek R1' },
  { id: 'grok-3', name: 'Grok-3' },
  { id: 'grok-3-reasoning', name: 'Grok-3 Reasoning' }
]

export default defineComponent({
  name: 'EvalTaskGenerator',
  setup() {
    const evaluationStore = useEvaluationStore()
    const versionStore = useVersionStore()
    const errorMessage = ref('')
    const isMaximized = ref(false)
    const isDragging = ref(false)
    const startPos = reactive({ x: 0, y: 0 })
    const windowPos = reactive({ x: window.innerWidth - 370, y: 20 }) // 370 = 350(窗口宽度) + 20(边距)
    const windowSize = reactive({ width: 350, height: 'auto' })
    const isLoading = ref(false)

    // 初始化store数据
    if (!evaluationStore.evaluationConfig.judges.length) {
      evaluationStore.evaluationConfig.judges = ['gpt-4o']
    }
    if (!evaluationStore.evaluationConfig.models.length) {
      evaluationStore.evaluationConfig.models = ['gpt-4o']
    }

    const windowStyle = computed(() => ({
      left: isMaximized.value ? '250px' : '0', // 假设侧边栏宽度为250px
      right: isMaximized.value ? '0' : 'auto',
      top: isMaximized.value ? '0' : '0',
      width: isMaximized.value ? 'calc(100vw - 250px)' : `${windowSize.width}px`, // 减去侧边栏宽度
      height: isMaximized.value ? 'calc(100vh - 20px)' : windowSize.height, // 减去顶部边距
      position: 'fixed' as 'fixed',
      transform: isMaximized.value ? 'none' : `translate(${Math.max(0, windowPos.x)}px, ${Math.max(0, windowPos.y)}px)`,
      transition: isDragging.value ? 'none' : 'transform 0.2s ease'
    } as any))

    const startDrag = (e: MouseEvent) => {
      if (isMaximized.value || (e.target as HTMLElement).tagName === 'INPUT' || (e.target as HTMLElement).tagName === 'TEXTAREA') {
        return
      }
      
      isDragging.value = true
      startPos.x = e.clientX - windowPos.x
      startPos.y = e.clientY - windowPos.y
      document.addEventListener('mousemove', onDrag)
      document.addEventListener('mouseup', stopDrag)
      e.preventDefault() // 防止文本选中
    }

    const onDrag = (e: MouseEvent) => {
      if (!isDragging.value) return
      // 计算新位置时使用初始的偏移量
      const newX = e.clientX - startPos.x
      const newY = e.clientY - startPos.y
      
      // 确保窗口不会移出视口
      const maxX = window.innerWidth - 350 // 固定宽度350px
      const maxY = window.innerHeight - 50 // 保留最小可见区域
      
      // 使用requestAnimationFrame实现流畅动画
      requestAnimationFrame(() => {
        windowPos.x = Math.max(0, Math.min(newX, maxX))
        windowPos.y = Math.max(0, Math.min(newY, maxY))
      })
    }

    const stopDrag = () => {
      isDragging.value = false
      document.removeEventListener('mousemove', onDrag)
      document.removeEventListener('mouseup', stopDrag)
    }

    const toggleMaximize = () => {
      isMaximized.value = !isMaximized.value
    }
    
    const canCreate = computed(() => {
      return evaluationStore.evaluationConfig.judges.length > 0 && 
             evaluationStore.evaluationConfig.models.length > 0 && 
             evaluationStore.selectedQuestionIds.length > 0
    })

    const removeQuestion = (id: number) => {
      evaluationStore.selectedQuestionIds = evaluationStore.selectedQuestionIds.filter(q => q !== id)
    }

    const createEvaluationTask = async () => {
      if (!versionStore.currentVersion?.ver_code) {
        errorMessage.value = '请先选择版本'
        return
      }
      
      isLoading.value = true
      errorMessage.value = ''
      try {
        await createTask({
          title: evaluationStore.evaluationConfig.title,
          description: evaluationStore.evaluationConfig.description,
          prompt: evaluationStore.evaluationConfig.prompt,
          version: versionStore.currentVersion.ver_code,
          judges: evaluationStore.evaluationConfig.judges,
          models: evaluationStore.evaluationConfig.models,
          questionIds: evaluationStore.selectedQuestionIds
        })
        evaluationStore.toggleEvaluationCreator(false)
      } catch (error) {
        errorMessage.value = '创建评测任务失败: ' + (error as Error).message
        console.error('创建评测任务失败:', error)
      } finally {
        isLoading.value = false
      }
    }
    
    return {
      availableJudges,
      availableModels,
      evaluationStore,
      canCreate,
      removeQuestion,
      createEvaluationTask,
      errorMessage,
      isLoading,
      isMaximized,
      toggleMaximize,
      windowStyle,
      startDrag
    }
  }
})
</script>

<style scoped>
.eval-task-generator {
  position: relative;
}

.floating-window {
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  z-index: 1000;
  display: flex;
  flex-direction: column;
  max-height: 80vh;
  overflow: hidden;
  width: 350px; /* 固定宽度 */
  transition: all 0.3s ease;
}

.window-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  border-bottom: 1px solid #eee;
  cursor: grab;
  user-select: none;
}

.window-header:active {
  cursor: grabbing;
}

.window-controls {
  display: flex;
  gap: 8px;
}

.window-header h2 {
  margin: 0;
  font-size: 18px;
  color: #2c3e50;
}

.close-btn,
.maximize-btn {
  background: none;
  border: none;
  font-size: 16px;
  cursor: pointer;
  color: #666;
  padding: 0 8px;
  width: 24px;
  height: 24px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.close-btn:hover,
.maximize-btn:hover {
  background-color: #f0f0f0;
  border-radius: 4px;
}

.close-btn:hover {
  color: #333;
}

.window-content {
  padding: 16px;
  overflow-y: auto;
  height: calc(100% - 60px); /* 减去标题栏高度 */
}

.error-message {
  color: red;
  margin-bottom: 16px;
  padding: 8px;
  background-color: #ffeeee;
  border-radius: 4px;
}

.form-group {
  margin-bottom: 20px;
}

.form-group label {
  display: block;
  margin-bottom: 8px;
  font-weight: bold;
  color: #666;
}

.task-title-input {
  width: 100%;
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
}

.task-description-input,
.task-prompt-input {
  width: 100%;
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
  min-height: 80px;
  margin-top: 8px;
}

.no-selection {
  color: #999;
  font-size: 14px;
  padding: 8px;
  text-align: center;
}

.selected-items {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  margin-top: 8px;
}

.selected-item {
  display: flex;
  align-items: center;
  background-color: #f0f0f0;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 14px;
}

.remove-btn {
  background: none;
  border: none;
  color: #999;
  cursor: pointer;
  margin-left: 4px;
  font-size: 14px;
  padding: 0 4px;
}

.remove-btn:hover {
  color: #ff4d4f;
}

.model-options-container {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 12px;
  margin-bottom: 12px;
}

.model-option {
  display: flex;
  align-items: center;
  gap: 8px;
}

.model-option input {
  margin: 0;
}

.action-buttons {
  margin-top: 20px;
}

.create-btn {
  width: 100%;
  padding: 8px 16px;
  background-color: #42b983;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.create-btn:hover {
  background-color: #3aa876;
}

.create-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
  background-color: #ccc;
}
</style>